﻿using System;
using System.Configuration;

namespace AutoExecuteSp
{
    public class ConfigReader
    {
        public static T GetValue<T>(string appKey)
        {
            string keyValue = ConfigurationManager.AppSettings[appKey];

            object returnValue = null;

            if (typeof(T) == typeof(string)) returnValue = keyValue;

            else if (typeof(T) == typeof(bool))
            {
                returnValue = "Y".Equals(keyValue, StringComparison.CurrentCultureIgnoreCase);
            }
            else if (typeof(T) == typeof(DateTime?)
                || typeof(T) == typeof(DateTime))
            {
                DateTime t;
                if (DateTime.TryParse(keyValue, out t))
                    returnValue = t;
            }
            return (T)returnValue;
        }

        public static void SetConfiguration(string key, string value)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection appSettings = configuration.AppSettings;

            if (appSettings == null) return;

            appSettings.Settings[key].Value = value;

            configuration.Save();
        }
    }
}
